package pagination

import (
	"github.com/jinzhu/gorm"
	"strconv"
)

type Pagination struct {
	Page        int   `json:"page" gorm:""`
	PageSize    int   `json:"page_size" gorm:""`
	PageCount   int   `json:"page_count" gorm:""`
	RecordCount int64 `json:"record_count" gorm:""`
	Path        string `json:"path"`
	Params     map[string]interface{} `json:"params"`
	query *gorm.DB
}

type PageLaber struct {
	PageCount    int   `json:"page_count"`
	PageCurrent  int   `json:"page_current"`
	PageNext     int   `json:"page_next"`
	PagePrev     int   `json:"page_prev"`
	RecordCount  int64   `json:"record_count"`
}

//加载分页组件
func InitPagination(pageSize, page int, query *gorm.DB, pageParams ... string) *Pagination {
	path := ""
	if len(pageParams) > 0 {
		path = pageParams[0]
	}
	pagination := &Pagination{
		Page:     page,
		PageSize: pageSize,
		Path: path,
	}

	var count int64
	var params = make(map[string]interface{}, 0)
	query.Count(&count)
	pagination.RecordCount = count
	pagination.PageCount = pagination.GetPageCount()
	pagination.query = query
	pagination.Params = params
	return pagination
}

//增加参数
func (p Pagination) PageParam(key string, value interface{})  {
	if v,ok := value.(int); ok {
		vstr := strconv.Itoa(v)
		p.Params[key] = vstr
	}
}

func (p Pagination) GetList(recordList interface{}) error  {
	offset := p.GetOffset()
	return p.query.Offset(offset).Limit(p.PageSize).Find(recordList).Error
}

//导出query
func (p Pagination) GetListQuery(query *gorm.DB) *gorm.DB {
	return query.Offset(p.GetOffset()).Limit(p.PageSize)
}

//获取页开始计数
func (p Pagination) GetOffset() int {
	page := p.GetPage()
	return (page - 1) * p.PageSize
}

//获取页数
func (p Pagination) GetPage() int {
	if p.Page < 1 {
		p.Page = 1
	}
	return p.Page
}

//获取总页数
func (p Pagination) GetPageCount() int {
	pageCount := int(p.RecordCount) / p.PageSize
	if int(p.RecordCount)%p.PageSize != 0 {
		pageCount++
	}
	return pageCount
}

//获取总记录数
func (p Pagination) GetRecordCount() int64 {
	return p.RecordCount
}

//获取上一页
func  (p Pagination) GetPrevPage() int  {
	page := p.GetPage()
	if page < 2 {
		return 1
	}
	return p.GetPage() - 1
}

//获取下一页
func   (p Pagination) GetNextPage() int  {
	page := p.GetPage()
	if page == p.GetPageCount() {
		return p.GetPageCount()
	}
	return p.GetPage() + 1
}

//获取分页标签
func (p Pagination) GetPageLaber() *PageLaber  {
	return &PageLaber{
		PageCount: p.GetPageCount(),
		PageCurrent: p.GetPage(),
		PageNext: p.GetNextPage(),
		PagePrev: p.GetPrevPage(),
		RecordCount: p.GetRecordCount(),
	}
}